import Vue from "vue";

const _toInterage = function (value) {
  value = value || "";
  value = value + "";
  value = value.replace(/\D/g, "");
  return value;
};

/**
 * @author {LDM}
 * @param {自定义指令名称} directiveName
 * @param {处理函数} funcName
 */
const getDirective = function (directiveName, funcName) {
  const selfDirective = Vue.directive(directiveName, {
    bind: function (el, binding, vnode) {
      el.addEventListener("compositionstart", onCompositionStart);
      el.addEventListener("compositionend", onCompositionEnd);
      if (el.nodeName === "input" || el.nodeName === "INPUT") {
        el.addEventListener("keyup", function (e) {
          if (e.target.composing) return;
          el.value = funcName(el.value, binding);
          vnode &&
            vnode.data &&
            vnode.data.model &&
            vnode.data.model.callback &&
            vnode.data.model.callback(funcName(el.value, binding));
        });
        el.addEventListener("blur", function (e) {
          if (e.target.composing) return;
          el.value = funcName(el.value, binding);
          vnode &&
            vnode.data &&
            vnode.data.model &&
            vnode.data.model.callback &&
            vnode.data.model.callback(funcName(el.value, binding));
        });
      } else {
        const item = vnode.child.$refs["input"];
        if (!item) return;
        item.addEventListener("keyup", function (e) {
          if (e.target.composing) return;
          item.value = funcName(item.value, binding);
          vnode &&
            vnode.data &&
            vnode.data.model &&
            vnode.data.model.callback &&
            vnode.data.model.callback(funcName(item.value, binding));
        });
        item.addEventListener("blur", function (e) {
          if (e.target.composing) return;
          item.value = funcName(item.value, binding);
          vnode &&
            vnode.data &&
            vnode.data.model &&
            vnode.data.model.callback &&
            vnode.data.model.callback(funcName(item.value, binding));
        });
      }
    },
    update: function (el, binding, vnode) {
      if (vnode.child) {
        const value =
          vnode.data.model.value || vnode.data.model.value === 0
            ? vnode.data.model.value + ""
            : "";
        const currentValue = funcName(value, binding) || null;
        vnode.child.currentValue = currentValue;
        vnode.data.model.callback(currentValue);
      }
    },
  });
  return selfDirective;
};

// 赋值变量 composing用于判断是否在拼写当中
const onCompositionStart = function (e) {
  e.target.composing = true;
};

const onCompositionEnd = function (e) {
  if (!e.target.composing) return;
  e.target.composing = false;
};

const interage = getDirective("interage", _toInterage);

export { interage };
